package auth

import (
	"sync"
)

type userList struct {
	users  map[string]userInfo
	locker sync.Mutex
}

func (u *userList) initList() {
	u.users = make(map[string]userInfo)
}

func NewUserList() (u userList) {
	u.initList()
	return
}

func (u *userList) Add(token session, name string, authority int) bool {
	u.locker.Lock()
	defer u.locker.Unlock()

	_, ok := u.users[token.Token]

	if !ok {
		info := userInfo{
			Name:      name,
			Token:     token,
			Authority: authority,
		}
		u.users[token.Token] = info
		return true
	}
	return false
}

func (u *userList) Remove(token string) {
	u.locker.Lock()
	defer u.locker.Unlock()

	_, ok := u.users[token]
	if ok {
		delete(u.users, token)
	}
}

func (u *userList) IsHave(token string) bool {
	u.locker.Lock()
	defer u.locker.Unlock()

	_, ok := u.users[token]
	return ok
}

func (u *userList) Get(token string) (userInfo, error) {
	u.locker.Lock()
	defer u.locker.Unlock()

	v, ok := u.users[token]
	if ok {
		return v, nil
	}
	return userInfo{}, ErrNotExist
}
